package com.hanxiaozhang.threadbase1ndedition.no4lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 〈一句话功能简述〉<br>
 * 〈ReentrantLock的lockInterruptibly〉
 * <p>
 * 使用ReentrantLock还可以调用lockInterruptibly方法，可以对线程interrupt方法做出响应，
 * 在一个线程等待锁的过程中，可以被打断。
 *
 *
 * @author hanxinghua
 * @create 2021/11/11
 * @since 1.0.0
 */
public class No3ReentrantLockLockInterruptibly {


    public static void main(String[] args) throws InterruptedException {

        ReentrantLock lock = new ReentrantLock();

        Thread t1 = new Thread(() -> {
            lock.lock();
            try {
                System.out.println("t1 start");
                // 睡眠时间 Integer.MAX_VALUE 或 1
                TimeUnit.SECONDS.sleep(1);
                System.out.println("t1 end");
            } catch (InterruptedException e) {
                System.out.println("interrupted!");
            } finally {
                lock.unlock();
            }
        }, "t1");
        t1.start();

        Thread t2 = new Thread(() -> {
            try {
                lock.lockInterruptibly();
                System.out.println("t2 start");
                TimeUnit.SECONDS.sleep(5);
                System.out.println("t2 end");
            } catch (InterruptedException e) {
                System.out.println("interrupted!");
                System.out.println(Thread.currentThread().isInterrupted());
            } finally {
                if (lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }
        },"t2");
        t2.start();

        TimeUnit.SECONDS.sleep(2);
        // 打断线程2的等待
        t2.interrupt();

    }


}
